package ic

import (
	"bytes"
	"fmt"
	"image"

	"github.com/chai2010/webp"
)

type WebPConverter struct{}

func (w *WebPConverter) SupportedFormat() string {
	return "WebP"
}

func (w *WebPConverter) FileExtension() string {
	return ".webp"
}

func (w *WebPConverter) MimeType() string {
	return "image/webp"
}

func (w *WebPConverter) Encode(img image.Image, options ...Options) ([]byte, error) {
	var buf bytes.Buffer

	// 合并选项
	opts := MergeOptions(options...)

	webpOptions := &webp.Options{
		Lossless: opts.Lossless,
		Quality:  float32(opts.Quality),
	}

	// 编码
	if err := webp.Encode(&buf, img, webpOptions); err != nil {
		return nil, fmt.Errorf("WebP编码失败: %v", err)
	}

	return buf.Bytes(), nil
}

func (w *WebPConverter) Decode(data []byte) (image.Image, error) {
	return webp.Decode(bytes.NewReader(data))
}
